<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use app\api\model\Pay;

class Alipay extends Index{
    /*支付*/
    public function pay(){
        $id = $_GET['id'];//订单id
        $where['id']=$id;
        $res=Db::name('orders')->where($where)->find();
        if($res['services']==2){
            $map1['id']=$res['s_id'];
            $result1=Db::name('service_market')->where($map1)->find();
            $object=$result1['goods_name'];
			$value = 2;
        }else{
            $map2['id']=$res['name'];
            $result2=Db::name('market_trading')->where($map2)->find();
            $object=$result2['username'];
			$value = 1;
        }
        $config = Pay::getConfig();
        //异步通知地址
        $config['notify_url']= "/index.php/api/alipay/notify_url";
		//同步跳转
		$config['return_url']="/index.php/index/person/order?value=$value";
        require_once 'Alipay/pagepay/service/AlipayTradeService.php';
        require_once 'Alipay/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';
        if($res){
            //商户订单号，商户网站订单系统中唯一订单号，必填
            //$out_trade_no = trim($_POST['WIDout_trade_no']);
            $out_trade_no =$res['order'];
            //订单名称，必填
            //$subject = trim($_POST['WIDsubject']);
            $subject =$object;
            //付款金额，必填
            //$total_amount = trim($_POST['WIDtotal_amount']);
            //$total_amount =$res['money'];
			$total_amount =0.1;
            //商品描述，可空
            //$body = trim($_POST['WIDbody']);
            $body ='';
            //构造参数
            $payRequestBuilder = new \AlipayTradePagePayContentBuilder();
            $payRequestBuilder->setBody($body);
            $payRequestBuilder->setSubject($subject);
            $payRequestBuilder->setTotalAmount($total_amount);
            $payRequestBuilder->setOutTradeNo($out_trade_no);

            $aop = new \AlipayTradeService($config);

            /**
             * pagePay 电脑网站支付请求
             * @param $builder 业务参数，使用buildmodel中的对象生成。
             * @param $return_url 同步跳转地址，公网可以访问
             * @param $notify_url 异步通知地址，公网可以访问
             * @return $response 支付宝返回的信息
             */
            $response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);

            //输出表单
            var_dump($response);
        }else{
            $this->_jsonp('1001', '查询订单失败', null);
        }

    }
    /**支付异步通知*/
    public function notify_url(){
        /**回调支付结果修改订单状态*/
        //dump($trade);
        //$toltal_amount = $trade['total_amount'];         //总价钱
        //$sign = $trade['sign'];                        //异步返回的验签
        $out_trade_no = input('post.out_trade_no');       //原支付请求的订单号18052167856
        $data1['total_amount']=input('post.total_amount');//通知时间
        $trade_status=input('post.trade_status');//TRADE_SUCCESS
        $data1['time']=strtotime(input('post.notify_time'));//通知时间
        //$data1['subject']=$trade['subject'];
        $data1['trade_no']=input('post.trade_no');//交易流水号
        //$data1['buyer_id']=$trade['buyer_id'];
        //$data1['buyer_email']=$trade['buyer_logon_id'];
        //$data1['total_fee']=$trade['total_amount'];
        $data1['out_trade_no']=$out_trade_no;
        
            //修改订单的状态，status和is_pay
            $where['order']=  $out_trade_no;
//            $uid=Db::name('orders')->where($where)->find();
//            $data3['uid']=$uid['seller'];//发送平台消息：未建表

			$result = db('orders')->where($where)->find();
			if($result['services'] == 2){
				$data['static'] = 6;
				$data['statuc'] = 2;
				$data['status'] = 2;
				$data3['order_num']=$result['id'];
				$data3['order_status']=2;
				$data3['order_msg']='付款成功';
				$data3['time']=time();
			}else{
				$data['statuc'] = 3;
				$data['status'] = 3;
				$data3['order_num']=$result['id'];
				$data3['order_status']=3;
				$data3['order_msg']='success';
				$data3['time']=time();
				$data4['static'] = 4;
				db('offer')->where('order_id',$result['id'])->where('uid',$result['username'])->update($data4);
			}
            $data1['is_pay'] = 1;
            $data1['order_status'] = 2;
            
		if($trade_status=="TRADE_SUCCESS"){	
            $show=Db::name('orders')->where($where)->update($data);
            $res1=Db::name('order_msg')->insert($data3);
            $res=Db::name('trade_info')->insert($data1);
            if($show&&$res){
                echo "success";
            }else{
                echo 'fail';
            }
        }else{
            echo "fail";
        }
    }
    //退款
    public function refund()
    {
		
        $id = $_REQUEST['id'];//订单id
        $where['o.id']=$id;
        $res = Db::name('orders')->alias('o')->join('zgh_trade_info i', 'i.out_trade_no=o.order')->where($where)->field('o.services,i.*')->find();
		
        $config = Pay::getConfig();//配置文件
        if ($res && $res['is_pay'] == 1 && $res['order_status'] == 2) {
            require_once 'Alipay/aop/AopClient.php';
            require_once 'Alipay/aop/request/AlipayTradeRefundRequest.php';
            //$out_trade_no=$info['order_number'];
            //$username=$info['username'];
            $trade_no = $res['trade_no'];
            $out_trade_no = $res['out_trade_no'];
            $refund_amount = $res['total_amount'];
            $aop = new \AopClient();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = $config['app_id'];
            $aop->rsaPrivateKey = $config['merchant_private_key'];
            //$aop->alipayrsaPublicKey = $config['alipay_public_key'];
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset = 'UTF-8';

            $aop->format = 'json';
            $request = new \AlipayTradeRefundRequest ();
            $request->setNotifyUrl("");
            $time = date('YmdHis') . rand(10000, 999999);
            $request->setBizContent("{" .
                "\"out_trade_no\":\"$out_trade_no\"," .
                "\"trade_no\":\"$trade_no\"," .
                "\"refund_amount\":$refund_amount," .
                "\"refund_reason\":\"交易退款\"," .
                "\"out_request_no\":\"$time\"," .
                "\"operator_id\":\"ZJNB001\"," .
                "\"store_id\":\"知果汇\"," .
                "\"terminal_id\":\"知果汇001\"" .
                "}");
            $result = $aop->execute($request);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
		
            if (!empty($resultCode) && $resultCode == '10000') {
                //修改订单状态
                if($res['services']==2){
                    //服务商品修改
                    $map['id']=$id;//服务订单id
                    $data['static']=3;
                    $data['statuc']=11;
                    $show['order']=$res['out_trade_no'];
                    $show['static']=2;
                    $res1= Db::name('refund')->where($show)->distinct(true)->order('id desc')->find();
                    $where1['id']=$res1['id'];
                    $data1['static']=3;
                    //$where2['id']=$res['id'];
                    $data2['order_status']=11;
                    $data2['is_pay']=2;
					$data2['out_trade_no']=$out_trade_no;
					$data2['trade_no']=$trade_no;
					$data2['total_amount']=$refund_amount;
					$data2['time']=time();
                    $data3['order_num']=$id;
                    $data3['order_status']=11;
                    $data3['order_msg']='成功退款';
                    $data3['time']=time();
                    $status = 0;
                    Db::startTrans();
                    try {
                        Db::name('orders')->where($map)->update($data);
                        Db::name('refund')->where($where1)->update($data1);
                        Db::name('trade_info')->insert($data2);
                        Db::name('order_msg')->insert($data3);
                        // 提交事务
                        Db::commit();
                        $status = 1;
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                    }
                    if ($status == 1) {
                        action_log('退款', 'log_admin',1);
                        $this->json('200', '成功退款', null);
                       // echo '成功';
                    } else {
                        action_log('退款', 'log_admin');
                        $this->json('1000', '已成功退款,数据修改失败', null);
                        //echo '是啊比';
                    }
                }else{
                    //交易商品修改
                    //echo 1;
                }

            } else {
                $this->json('1000', '退款失败', null);
                //echo 2;
            }
        }
    }
    //转账
    public function account(){
		
		$id = $_REQUEST['id'];//订单id
        $where['o.id']=$id;//连接user表
        $res = Db::name('orders')->alias('o')->join('zgh_user i', 'i.uid=o.seller')->where($where)->field('o.*,i.alipay')->find();
		if($res['services'] == 1){
			$name = db('market_trading')->where('id',$res['name'])->value('username');
		}else{
			$name = db('service_market')->where('id',$res['s_id'])->value('goods_name');
		}
		$res1 = Db::name('authentication_personal')->where('uid',$res['seller'])->find();
        $res2 = Db::name('authentication_enterprise')->where('uid',$res['seller'])->find();
        if($res1){
            $nick=$res1['nick'];
            $alipay=$res1['alipay'];
        }else{
            $nick=$res2['nick'];
            $alipay=$res2['alipay'];
        }
        $order=$res['order'];
		//$money=$res['money'];
		$money=0.1;
		//$alipay=$res['alipay'];
//        $preg = '/^2088\d{14}$/i';
//        preg_match_all($preg, $res['alipay'], $matches);
//        $pic = $matches != null ? $matches[1] : '';
        $config = Pay::getConfig();//配置文件
        require_once 'Alipay/aop/AopClient.php';
        require_once 'Alipay/aop/request/AlipayFundTransToaccountTransferRequest.php';
        $aop = new \AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $config['app_id'];
        $aop->rsaPrivateKey = $config['merchant_private_key'];
        //$aop->alipayrsaPublicKey=$config['alipay_public_key'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayFundTransToaccountTransferRequest ();
        $request->setBizContent("{" .
            "\"out_biz_no\":\"$order\"," .
            "\"payee_type\":\"ALIPAY_LOGONID\"," .
            "\"payee_account\":\"$alipay\"," .
            "\"amount\":\"$money\"," .
            "\"payer_show_name\":\"$name\"," .
            "\"payee_real_name\":\"$nick\"," .
            "\"remark\":\"转账备注\"" .
            "}");
        //这里做判断订单是否是打款
		if($alipay){
			if($res['services']==2){
            //服务商品
				if($res['static']==3){
					$result = $aop->execute ( $request);
					$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
					$resultCode = $result->$responseNode->code;
					if(!empty($resultCode)&&$resultCode == 10000){
						//订单状态变化
						$where1['id']=$id;
						$data1['static']=4;
						$data1['status']=9;
						$data2['order_num']=$id;
						$data2['order_status']=9;
						$data2['type']=2;
						$data2['order_msg']='成功打款卖家';
						$data2['time']=time();
						$data3['trade_no']=$result->$responseNode->order_id;
						$data3['out_trade_no']=$result->$responseNode->out_biz_no;
						$data3['time']=time();
						$data3['is_pay']=3;
						$data3['total_amount']=$res['money'];
						$data3['order_status']=9;
						$status = 0;
						Db::startTrans();
						try {
							Db::name('orders')->where($where1)->update($data1);
							Db::name('trade_info')->insert($data3);
							Db::name('order_msg')->insert($data2);
							// 提交事务
							Db::commit();
							$status = 1;
						} catch (\Exception $e) {
							// 回滚事务
							Db::rollback();
						}
						if ($status == 1) {
							action_log('退款', 'log_admin',1);
							$this->_jsonp('200', '成功打款卖家', null);
						} else {
							action_log('退款', 'log_admin');
							$this->_jsonp('1000', '已成功打款,数据修改失败', null);
						}
					} else {
						$this->_jsonp('1000', '打款失败', null);
					}
				}else{
					$this->_jsonp('1000', '订单状态错误', null);
				}
			}else{
				if($res['status'] == 7){
				//交易商品
				$result = $aop->execute ( $request);
					$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
					$resultCode = $result->$responseNode->code;
					if(!empty($resultCode)&&$resultCode == 10000){
						//订单状态变化
						$where1['id']=$id;
						$data1['static'] = 4;
						$data1['status'] = 8;
						$data2['order_num']=$id;
						$data2['order_status']=9;
						$data2['order_msg']='成功打款卖家';
						$data2['time']=time();
						$data3['trade_no']=$result->$responseNode->order_id;
						$data3['out_trade_no']=$result->$responseNode->out_biz_no;
						$data3['time']=time();
						$data3['is_pay']=3;
						$data3['total_amount']=$res['money'];
						$data3['order_status']=9;
						$status = 0;
						Db::startTrans();
						try {
							Db::name('orders')->where($where1)->update($data1);
							Db::name('trade_info')->insert($data3);
							Db::name('order_msg')->insert($data2);
							// 提交事务
							Db::commit();
							$status = 1;
						} catch (\Exception $e) {
							// 回滚事务
							Db::rollback();
						}
						if ($status == 1) {
							action_log('打款', 'log_admin',1);
							$this->_jsonp('200', '成功打款卖家', null);
						} else {
							action_log('打款', 'log_admin');
							$this->_jsonp('1000', '已成功打款,数据修改失败', null);
						}
					} else {
						$this->_jsonp('1000', '打款失败', null);
					}
				}
			}
		}else{
			$this->_jsonp('1000', '卖家还未设置支付宝', null);
		}
        

    }


}